package com.haochang.base;

import java.util.Timer;
import java.util.TimerTask;

import com.basewin.log.LogUtil;
import com.basewin.services.ServiceManager;
import com.haochang.chunkvod.app.common.VodConstant;
import com.haochang.chunkvod.app.config.AppConifg;
import com.haochang.chunkvod.app.config.DeviceConfig;
import com.haochang.chunkvod.app.config.ServerConfig;
import com.haochang.chunkvod.app.config.ServerConfig.ServerAddressEnum;
import com.haochang.chunkvod.app.exception.CrashHandler;
import com.haochang.chunkvod.app.utils.HelperUtils;
import com.haochang.chunkvod.app.utils.LoadImageUtils;
import com.haochang.chunkvod.service.RoomStatusService;
import com.haochang.chunkvod.tools.thirdparty.network.http.HttpClientEx;
import com.haochang.chunkvod.tools.thirdparty.network.http.client.AsyncHttpClient;
import com.haochang.chunkvod.tools.vod.goods.ShoppingCartManager;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

/**
 * Created by Eclipse.
 * User: lxl
 * Date: 2016年5月10日
 * Time: 下午4:15:33
 * Des:程序初始化相关
 */
public class BaseApplication extends com.basewin.base.application.BaseApplication
{
	public static final ServerAddressEnum CURRENT_ENVIRONMENT = ServerAddressEnum.SERVERADDRESS_ONLINE;//SERVERADDRESS_QA SERVERADDRESS_ONLINE
	public static Context appContext = null;
	public static AsyncHttpClient appHttpClient = null;
	private Timer timer;
	private TimerTask timerTask;

	@Override
	public void onCreate()
	{
		super.onCreate();
		if (BaseApplication.appContext == null)
		{
			//防止多进程调用造成的App初始化多次
			String appName = this.getCurProcessName(this.getApplicationContext());
			appContext = this.getApplicationContext();
			if (!TextUtils.isEmpty(appName) && appName.equals(getApplicationContext().getPackageName()))
			{
				//初始化App相关配置
				initApplicationConfig();
				initHttp();
			}
		}
	}

	private void initHttp()
	{
		//防止appHttpClient因网络异常导致为空 设置为为空时重新获取
		if (appHttpClient == null)
			appHttpClient = HttpClientEx.getHttpClient();
	}

	/**
	 * 上下文
	 */
	public static Context getContext()
	{
		return appContext;
	}

	/**
	 * App相关配置初始化
	 */
	private void initApplicationConfig()
	{
		ServerConfig.initServerConifg(CURRENT_ENVIRONMENT);
		initNetworkIp();
		DeviceConfig.init();
		EventProxy.init();
		//应用所需环境进行校验
		AppConifg.init();
		//添加异常捕获模块.
		CrashHandler.getInstance().init(appContext);
		CrashHandler.getInstance().collectCrashDeviceInfo(appContext);
		//初始化 ImageLoader
		LoadImageUtils.initImageLoader(appContext);
		initTimer();
		//startService();
		//第三方pos机初始化
		LogUtil.closeLog();
		if (DeviceConfig.isUseP2000Device())
		{
			try
			{
				ServiceManager.getInstence().init(appContext);
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}

	/**
	 * 启动房间状态监听服务
	 */
	private void startService()
	{
		Intent intent = new Intent(appContext, RoomStatusService.class);
		intent.setAction("Vod.RoomStatus");
		startService(intent);
	}

	/**
	 * 初始化网络ip
	 */
	private void initNetworkIp()
	{
		if (!TextUtils.isEmpty(HelperUtils.getHelperInstance().getSValue(VodConstant.IP_CHOOSED_SHOP, ""))
				&& !TextUtils.isEmpty(HelperUtils.getHelperInstance().getSValue(VodConstant.IP_CHOOSED, "")))
		{
			ServerConfig.qATestEnvironmentIp = HelperUtils.getHelperInstance().getSValue(VodConstant.IP_CHOOSED, "");
			ServerConfig.serverIp = ServerConfig.qATestEnvironmentIp;
		}
	}

	/**
	 * 全局timer，用于每半小时检查一次购物车，不满足条件的就清空购物车
	 */
	private void initTimer()
	{
		timer = new Timer();
		timerTask = new TimerTask()
		{
			@Override
			public void run()
			{
				ShoppingCartManager.checkGoods();
			}
		};
		timer.schedule(timerTask, 36000000, 3600000);
	}

	/**
	 * 获取当前进程名称
	 *
	 * @param context .
	 * @return .
	 */
	private String getCurProcessName(Context context)
	{
		String returnValue = null;
		int pid = android.os.Process.myPid();
		ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses())
		{
			if (appProcess.pid == pid)
				returnValue = appProcess.processName;
		}
		return returnValue;
	}

	@Override
	public void onTerminate()
	{
		// 程序终止的时候执行
		cancelTask();
		super.onTerminate();
	}

	private void cancelTask()
	{
		if (timer != null)
		{
			timer.cancel();
			timer = null;
		}
		if (timerTask != null)
		{
			timerTask.cancel();
			timerTask = null;
		}
	}
}
